<?php
namespace App\Traits;
/*

2019/1/18
*/
use Illuminate\Support\Facades\{Log, Cache};
use League\OAuth2\Server\{CryptKey, CryptTrait};
use League\OAuth2\Server\Grant\AbstractGrant;
use League\OAuth2\Server\Entities\ScopeEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use Laravel\Passport\{Passport, Token, Client};
use Laravel\Passport\Bridge\{AccessToken, ClientRepository, Scope};

trait RevokeOldTokens 
{
	use CryptTrait;

	// token_id 转换成相应的 access_token
    public function tokenId2Bearer($tokenId)
	{
        $userId = $this->user_id;
		$token = Token::findOrFail($tokenId);
		$clientId = $token->client_id;
        $request = app()->get('request');
		$scope = $request->input('scope', '*');
		$clientSecret = $request->input('clientSecret', $token->client->secret);
		$grantType = in_array($clientId, [1, 4, 5, ]) ? 'personal_access':'password';
		$grantType = $request->input('grantType', $grantType);
		$privateKey = new CryptKey('file://'.Passport::keyPath('oauth-private.key'), null, false);
        $scopes = $this->getScopesEntityByIdentifiers($scope);
        $accessToken = (new AccessToken($userId, $scopes));
        $clientRepository = app()->make(ClientRepository::class);
        $client = $clientRepository->getClientEntity($clientId, $grantType, $clientSecret, true); 
        $accessToken->setClient($client);
        $accessToken->setUserIdentifier($userId);
        $accessToken->setExpiryDateTime((new \DateTime())->add(Passport::tokensExpireIn()));
        $maxGenerationAttempts = AbstractGrant::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
        while ($maxGenerationAttempts-- > 0) { $accessToken->setIdentifier($tokenId); }
		$responseParams = [
			'token_type'   => 'Bearer',
			'expires_in'   => $accessToken->getExpiryDateTime()->getTimestamp() - (new \DateTime())->getTimestamp(),
			'access_token' => (string) $accessToken->convertToJWT($privateKey),
		];
/*
		$refreshToken = $this->encrypt(
			json_encode(
				[
					'client_id'        => $accessToken->getClient()->getIdentifier(),
					'refresh_token_id' => $this->refreshToken->getIdentifier(),
					'access_token_id'  => $accessToken->getIdentifier(),
					'scopes'           => $accessToken->getScopes(),
					'user_id'          => $accessToken->getUserIdentifier(),
					'expire_time'      => $this->refreshToken->getExpiryDateTime()->getTimestamp(),
				]
			)
		);
		$responseParams['refresh_token'] = $refreshToken;
*/
        return $responseParams;
    }

    private function getScopesEntityByIdentifiers($scopes) 
	{
        $scopesList = array_filter(explode(' ', trim($scopes)), function ($scope) {
            return !empty($scope);
        });
        $validScopes = [];
        foreach ($scopesList as $scopeItem) {
            $scope = new Scope($scopeItem);
            if ($scope instanceof ScopeEntityInterface === false) {
                throw OAuthServerException::invalidScope($scopeItem);
            }
            $validScopes[] = $scope;
        }
        return $validScopes;
    }

} 
/* end */